<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>WebSocketDemo</title>
  </head>
  <body>
    <button id="connect">连接</button>
    <button id="send" disabled="true">发送数据</button>
    <br />
    从服务端接收到的数据如下: <br />
    <p id="recv"></p>
    <script>
      var connect = document.querySelector('#connect')
      var send = document.querySelector('#send')
      var recv = document.querySelector('#recv')
      let ws = null
      connect.onclick = function () {
        ws = new WebSocket('ws://localhost:9998')

        ws.onopen = () => {
          console.log('连接服务端成功了')
          send.disabled = false
        }
        ws.onclose = () => {
          console.log('连接服务器失败(onclose)')
          send.disabled = true
        }
        ws.onmessage = (msg) => {
          console.log('接收到服务端发过来的数据了:', msg)

          // msg 是事件对象
          // msg.data是字符串,通过parse可以转换为对象
          // recvData = JSON.parse(msg.data)
          // console.log(recvData)

          // msg.data是字符串,所以可以直接显示在innerHTML
          recv.innerHTML = msg.data
        }
      }
      send.onclick = function () {
        // console.log('send running...')
        ws.send(
          JSON.stringify({
            action: 'fullScreen',
            socketType: 'fullScreen',
            chartName: 'trend',
            value: true
          })
        )
      }
    </script>
  </body>
</html>
